<?php

namespace App\Admin\Controllers;

use App\Models\CustomerModel;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Controllers\HasResourceActions;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Show;
use GuzzleHttp\Client;

class CustomerController extends AdminController
{
    use HasResourceActions;

    protected $title = '客户';

    public function index(Content $content)
    {
        return $content
            ->header(trans('admin.customer'))
            ->description(trans('admin.list'))
            ->body($this->grid()->render());
    }

    public function getResult(string $keyword, $page = 1){
        try {
            $client   = new Client(['verify' => false]);
            $res      = $client->request(
                'POST',
                'https://tool.musicheng.com/lhkeyword/getlhkeywordlist',
                [
                    'multipart' => [
                        [
                            'name'     => 'sort',
                            'contents' => 'moods'
                        ],
                        [
                            'name'     => 'order',
                            'contents' => 'desc'
                        ],
                        [
                            'name'     => 'searchparams',
                            'contents' => '{"lhword":"水电费"}'
                        ],
                    ],
                    'proxy'     => [
                        'http' => '127.0.0.1:8888', //http协议的
                        //https协议的,带用户名密码验证的代理
                        //             'https' => 'http://username:password@localhost:9124',
                        'no'   => ['.mit.edu', 'foo.com']    // 无需代理的域名
                    ],
                    'headers'   => [
                        'User-Agent' => 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1',
                        //             'Accept'     => 'application/json',
                        //             'X-Foo'      => ['Bar', 'Baz']
                        'Cookie'     => "Hm_lvt_23c29ef18f57ef3419152a651c437547=1598629381; _ga=GA1.2.857115032.1598629384; _gid=GA1.2.784574927.1598629384; _gat=1; _gat_gtag_UA_129654797_1=1; lmkb=loginname=whjsdhr&chsavepsw=1&token=f881b239a4d12b698b044a4d3587026b&dt=1598888596; plcug=tik=M416ggkb6ccN688kk8ckM686k&token=04&isq=1&dt=1601221396; ASP.NET_SessionId=4lgcwrngji1hptudmoa2kqkl; otinfo=_siNt=1&_clri=5183398665563528685&_otm=1598629399; SignalRID=1_5183398665563528685; expcode5183398665563528685=expdt=2021-07-16&date=1598629399; Hm_lpvt_23c29ef18f57ef3419152a651c437547=1598629406"
                    ]
                ]
            );
            $response = $res->getBody()->getContents();
            $response = json_decode($response, true);
            if (!isset($response['Success']) || !$response['Success']) {
                throw new \Exception('获取失败');
            }
            dump($response);
            exit;
        } catch (\Throwable | \Exception $exception) {
            echo "出错了";
            $responseBody = $exception->getResponse()->getBody()->getContents();
            dump($responseBody);
            exit;
            //       //$responseBody = $exception->getResponse()->getBody(true);有的版本可能是这样
            //       //       preg_match_all('/<div class="text-tip[^>]*([\s\S]*?)<\/div>/i', $responseBody, $matches);
            //       preg_match_all('/<div class="text-tip">*([\s\S]*?)<\/div>/i', $responseBody, $matches);
            //       $matches = array_filter($matches);
            //       if ($matches) {
            //          dump($matches[1] ?? '请求错误1');
            //       }
            //       try {
            //          $responseBody = json_decode($responseBody, true);
            //          if (is_array($responseBody) && $responseBody) {
            //             dump($responseBody['code'][0] ?? '请求错误2');
            //             exit;
            //          }
            //          dump($responseBody);
            //          exit;
            //       } catch (\think\Exception | Throwable $e) {
            //          dump('请求错误3');
            //       }
            //       dump($responseBody);
            //       exit;
        }
    }
    
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $this->getResult("水电费", 1);
        $grid = new Grid(new CustomerModel());

        $grid->customer_id('客户ID')->sortable();
        //        $grid->project()->name('应用');
        $grid->name('客户名字');
        $grid->phone('联系方式');
        $grid->identity('身份识别码');
        $states = [
            'on'  => ['value' => 1, 'text' => '正常'],
            'off' => ['value' => 0, 'text' => '拉黑'],
        ];
        $grid->status('状态')->switch($states);

        $grid->company_name('单位名');
        $grid->company_address('单位地址');
        $grid->created_at('添加时间')->sortable();

        $grid->filter(function ($filter) {
            $filter->column(1 / 2, function ($filter) {
                $filter->where(function ($query) {
                    $query->where('name', 'like', "%{$this->input}%")
                        ->orWhere('phone', 'like', "%{$this->input}%")
                        ->orWhere('identity', 'like', "%{$this->input}%")
                        ->orWhere('company_name', 'like', "%{$this->input}%");
                }, '关键词')->placeholder('名字/联系方式/识别码/单位名称');
            });

            $filter->column(1 / 2, function ($filter) {
                $filter->equal('status')->radio([
                                                    1 => '正常',
                                                    0 => '拉黑',
                                                ]);
            });
        });

        return $grid;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new CustomerModel());
        $form->display('customer_id', 'ID');
        $form->text('name', '客户名字')->rules('required');
        $form->text('phone', '联系方式')->rules('required|integer|digits_between:7,11');
        $form->text('identity', '身份识别码')->required();
        $form->text('company_name', '单位名')->required();
        $form->text('company_address', '单位地址')->required();
        $states = [
            'on'  => ['value' => 1, 'text' => '正常', 'color' => 'success'],
            'off' => ['value' => 0, 'text' => '拉黑', 'color' => 'danger'],
        ];
        $form->switch('status', '状态')->states($states);

        $form->disableCreatingCheck();
        $form->disableEditingCheck();
        $form->disableViewCheck();
        $form->display('created_at', 'Created At');
        $form->display('updated_at', 'Updated At');
        return $form;
    }

    /**
     * Create interface.
     *
     * @return Content
     */
    public function create(Content $content)
    {
        return $content
            ->header(trans('admin.customer'))
            ->description(trans('admin.create'))
            ->body($this->form());
    }

    /**
     * Edit interface.
     *
     * @param $id
     *
     * @return Content
     */
    public function edit($id, Content $content)
    {
        return $content
            ->header(trans('admin.customer'))
            ->description(trans('admin.edit'))
            ->body($this->form()->edit($id));
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    public function detail($id)
    {
        $customer = CustomerModel::findOrFail($id);
        $show    = new Show($customer);
        $show->panel()
            ->style('primary')
            ->title('客户详情');
        $show->customer_id('客户ID');
        $show->name('客户名');
        $show->phone('联系方式');
        $show->identity('身份识别码');
        $show->company_name('单位名称');
        $show->company_address('单位地址');
        $show->status('状态')->using(['1' => '正常', '0' => '拉黑']);
        $show->created_at(trans('admin.created_at'));

        $show->updated_at(trans('admin.updated_at'));
        return $show;
    }
}
